package com.example.dictionary.controller;

import com.example.dictionary.service.DomainManagementService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 词汇领域管理REST API控制器
 * 提供领域的增删改查功能
 */
@RestController
@RequestMapping("/api/domains")
public class DomainController {
    
    private static final Logger log = LoggerFactory.getLogger(DomainController.class);
    
    private final DomainManagementService domainManagementService;
    
    public DomainController(DomainManagementService domainManagementService) {
        this.domainManagementService = domainManagementService;
    }
    
    /**
     * 获取所有领域
     */
    @GetMapping
    public ResponseEntity<List<DomainManagementService.Domain>> getAllDomains() {
        try {
            List<DomainManagementService.Domain> domains = domainManagementService.getAllDomains();
            return ResponseEntity.ok(domains);
        } catch (Exception e) {
            log.error("获取所有领域失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取所有领域名称
     */
    @GetMapping("/names")
    public ResponseEntity<List<String>> getAllDomainNames() {
        try {
            List<String> names = domainManagementService.getAllDomainNames();
            return ResponseEntity.ok(names);
        } catch (Exception e) {
            log.error("获取所有领域名称失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取领域数量
     */
    @GetMapping("/count")
    public ResponseEntity<Map<String, Integer>> getDomainCount() {
        try {
            int count = domainManagementService.getDomainCount();
            return ResponseEntity.ok(Map.of("count", count));
        } catch (Exception e) {
            log.error("获取领域数量失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 根据名称获取领域
     */
    @GetMapping("/{domainName}")
    public ResponseEntity<DomainManagementService.Domain> getDomain(@PathVariable String domainName) {
        try {
            Optional<DomainManagementService.Domain> domain = domainManagementService.getDomain(domainName);
            return domain.map(ResponseEntity::ok)
                    .orElse(ResponseEntity.notFound().build());
        } catch (Exception e) {
            log.error("获取领域失败: {}", domainName, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 检查领域是否存在
     */
    @GetMapping("/{domainName}/exists")
    public ResponseEntity<Map<String, Boolean>> existsDomain(@PathVariable String domainName) {
        try {
            boolean exists = domainManagementService.existsDomain(domainName);
            return ResponseEntity.ok(Map.of("exists", exists));
        } catch (Exception e) {
            log.error("检查领域是否存在失败: {}", domainName, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 搜索领域（按关键词）
     */
    @GetMapping("/search")
    public ResponseEntity<List<DomainManagementService.Domain>> searchDomains(@RequestParam(required = false) String keyword) {
        try {
            List<DomainManagementService.Domain> domains = domainManagementService.searchDomains(keyword);
            return ResponseEntity.ok(domains);
        } catch (Exception e) {
            log.error("搜索领域失败: {}", keyword, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 创建新领域
     */
    @PostMapping
    public ResponseEntity<DomainManagementService.Domain> createDomain(@RequestBody CreateDomainRequest request) {
        try {
            if (request.getName() == null || request.getName().trim().isEmpty()) {
                return ResponseEntity.badRequest().build();
            }
            
            DomainManagementService.Domain domain = domainManagementService.addDomain(
                    request.getName(), 
                    request.getDescription()
            );
            
            return ResponseEntity.status(HttpStatus.CREATED).body(domain);
        } catch (IllegalArgumentException e) {
            log.warn("创建领域失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            log.error("创建领域失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 更新领域
     */
    @PutMapping("/{domainName}")
    public ResponseEntity<DomainManagementService.Domain> updateDomain(
            @PathVariable String domainName,
            @RequestBody UpdateDomainRequest request) {
        try {
            Optional<DomainManagementService.Domain> domain = domainManagementService.updateDomain(
                    domainName,
                    request.getName(),
                    request.getDescription()
            );
            
            return domain.map(ResponseEntity::ok)
                    .orElse(ResponseEntity.notFound().build());
        } catch (IllegalArgumentException e) {
            log.warn("更新领域失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            log.error("更新领域失败: {}", domainName, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 删除领域
     */
    @DeleteMapping("/{domainName}")
    public ResponseEntity<Map<String, String>> deleteDomain(@PathVariable String domainName) {
        try {
            boolean deleted = domainManagementService.removeDomain(domainName);
            if (deleted) {
                return ResponseEntity.ok(Map.of("message", "领域删除成功", "domainName", domainName));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("删除领域失败: {}", domainName, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取真实领域词
     * 根据映射、同义词查询等逻辑获取实际使用的领域词
     */
    @GetMapping("/actual/{domainWord}")
    public ResponseEntity<Map<String, String>> getActualDomainWord(@PathVariable String domainWord) {
        try {
            String actualWord = domainManagementService.getActualDomainWord(domainWord);
            return ResponseEntity.ok(Map.of(
                    "domainWord", domainWord,
                    "actualDomainWord", actualWord
            ));
        } catch (Exception e) {
            log.error("获取真实领域词失败: {}", domainWord, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取所有领域词映射
     */
    @GetMapping("/mappings")
    public ResponseEntity<Map<String, String>> getAllDomainMappings() {
        try {
            Map<String, String> mappings = domainManagementService.getAllDomainMappings();
            return ResponseEntity.ok(mappings);
        } catch (Exception e) {
            log.error("获取领域词映射失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取领域词映射
     */
    @GetMapping("/mappings/{domainWord}")
    public ResponseEntity<Map<String, String>> getDomainMapping(@PathVariable String domainWord) {
        try {
            return domainManagementService.getDomainMapping(domainWord)
                    .map(mappedWord -> ResponseEntity.ok(Map.of(
                            "domainWord", domainWord,
                            "actualDomainWord", mappedWord
                    )))
                    .orElse(ResponseEntity.notFound().build());
        } catch (Exception e) {
            log.error("获取领域词映射失败: {}", domainWord, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 添加领域词映射
     */
    @PostMapping("/mappings")
    public ResponseEntity<Map<String, String>> addDomainMapping(@RequestBody AddMappingRequest request) {
        try {
            if (request.getDomainWord() == null || request.getDomainWord().trim().isEmpty()) {
                return ResponseEntity.badRequest().build();
            }
            if (request.getActualDomainWord() == null || request.getActualDomainWord().trim().isEmpty()) {
                return ResponseEntity.badRequest().build();
            }
            
            domainManagementService.addDomainMapping(
                    request.getDomainWord(),
                    request.getActualDomainWord()
            );
            
            return ResponseEntity.ok(Map.of(
                    "message", "映射添加成功",
                    "domainWord", request.getDomainWord(),
                    "actualDomainWord", request.getActualDomainWord()
            ));
        } catch (IllegalArgumentException e) {
            log.warn("添加映射失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            log.error("添加领域词映射失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 删除领域词映射
     */
    @DeleteMapping("/mappings/{domainWord}")
    public ResponseEntity<Map<String, String>> deleteDomainMapping(@PathVariable String domainWord) {
        try {
            boolean deleted = domainManagementService.removeDomainMapping(domainWord);
            if (deleted) {
                return ResponseEntity.ok(Map.of("message", "映射删除成功", "domainWord", domainWord));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("删除领域词映射失败: {}", domainWord, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 创建领域请求DTO
     */
    public static class CreateDomainRequest {
        private String name;
        private String description;
        
        public String getName() {
            return name;
        }
        
        public void setName(String name) {
            this.name = name;
        }
        
        public String getDescription() {
            return description;
        }
        
        public void setDescription(String description) {
            this.description = description;
        }
    }
    
    /**
     * 更新领域请求DTO
     */
    public static class UpdateDomainRequest {
        private String name;
        private String description;
        
        public String getName() {
            return name;
        }
        
        public void setName(String name) {
            this.name = name;
        }
        
        public String getDescription() {
            return description;
        }
        
        public void setDescription(String description) {
            this.description = description;
        }
    }
    
    /**
     * 添加映射请求DTO
     */
    public static class AddMappingRequest {
        private String domainWord;
        private String actualDomainWord;
        
        public String getDomainWord() {
            return domainWord;
        }
        
        public void setDomainWord(String domainWord) {
            this.domainWord = domainWord;
        }
        
        public String getActualDomainWord() {
            return actualDomainWord;
        }
        
        public void setActualDomainWord(String actualDomainWord) {
            this.actualDomainWord = actualDomainWord;
        }
    }
}

